package java8;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 使用Stream和Lambda对文件进行处理
 * @author Zhaohui
 */
public class FileTest {

    public static void main(String[] args) throws IOException{
        //路径
        Path src = Paths.get(System.getProperty("user.dir"), "file.txt");
        Path tar = Paths.get(System.getProperty("user.dir"), "newFile.txt");
        //时间
        LocalDateTime localDateTime = LocalDateTime.now();
        String today = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"));
        //处理
        Stream<String> lines = Files.lines(src);
        List<String> list =  lines
                .filter(line -> line.contains("8"))
                .map(line -> line.replace("this is",today + ": operate file.txt by"))
                .collect(Collectors.toList());
        //写入
        Files.write(tar,list, StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING);
    }

}
